package com.it.admin.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.it.admin.service.AdminTagService;
import com.it.common.domain.dos.ArticleTagRelDO;
import com.it.common.domain.dos.TagDO;
import com.it.common.enums.ResponseCodeEnum;
import com.it.common.exception.BizException;
import com.it.common.mapper.ArticleTagRelMapper;
import com.it.common.mapper.TagMapper;
import com.it.common.model.vo.SelectRspVO;
import com.it.common.utils.PageResponse;
import com.it.common.utils.Response;
import lombok.extern.slf4j.Slf4j;
import com.it.admin.model.dto.tag.AddTagDto;
import com.it.admin.model.dto.tag.DeleteTagDto;
import com.it.admin.model.dto.tag.FindTagPageListDto;
import com.it.admin.model.dto.tag.SearchTagsDto;
import com.it.admin.model.vo.tag.FindTagPageListRspVO;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
@Slf4j
public class AdminTagServiceImpl extends ServiceImpl<TagMapper, TagDO> implements AdminTagService {

    @Resource
    private TagMapper tagMapper;

    @Resource
    private ArticleTagRelMapper articleTagRelMapper;

    @Override
    public Response addTags(AddTagDto addTagDto) {

        String creator = SecurityContextHolder.getContext().getAuthentication().getName();
        List<TagDO> tags = addTagDto.getTags().stream()
                .map(s -> {
                    TagDO tagDO = new TagDO();
                    tagDO.setName(s);
                    tagDO.setUpdater(creator);
                    tagDO.setCreateTime(LocalDateTime.now());
                    tagDO.setUpdateTime(LocalDateTime.now());
                    tagDO.setCreator(creator);
                    return tagDO;
                }).collect(Collectors.toList());

        try {
            tagMapper.insertBatch(tags);
        }catch (Exception e){
            log.info("该标签已存在",e);
        }
        return Response.success();
    }

    @Override
    public PageResponse findTagPageList(FindTagPageListDto findTagPageListDto) {
        Long current = findTagPageListDto.getCurrent();
        Long size = findTagPageListDto.getSize();
        String name = findTagPageListDto.getName();
        LocalDate startDate = findTagPageListDto.getStartDate();
        LocalDate endDate = findTagPageListDto.getEndDate();

        Page<TagDO> page = tagMapper.selectPageList(current, size, name, startDate, endDate);

        List<TagDO> records = page.getRecords();

        // do 转 vo
        List<FindTagPageListRspVO> vos = null;
        if(records.size() > 0){
            vos = records.stream().map(tagDO -> {
                FindTagPageListRspVO vo = new FindTagPageListRspVO();
                vo.setId(tagDO.getId());
                vo.setName(tagDO.getName());
                vo.setCreateTime(tagDO.getCreateTime());
                vo.setCreator(tagDO.getCreator());
                vo.setArticlesTotal(tagDO.getArticlesTotal());
                return vo;
            }).collect(Collectors.toList());
        }
        return PageResponse.success(page, vos);
    }


    @Override
    public Response deleteTag(DeleteTagDto deleteTagDto) {
        Long id = deleteTagDto.getId();
        Boolean flag = tagMapper.deleteTag(id);

        ArticleTagRelDO articleTagRelDO = articleTagRelMapper.selectOneByTagId(id);
        if(Objects.nonNull(articleTagRelDO)){
            log.warn("==> 此标签下包含文章，无法删除，tagId: {}", id);
            throw new BizException(ResponseCodeEnum.TAG_CAN_NOT_DELETE);
        }

        return flag ? Response.success() : Response.fail(ResponseCodeEnum.TAG_NOT_EXIST);
    }

    @Override
    public Response searchTags(SearchTagsDto searchTagsDto) {
        String key = searchTagsDto.getKey();
        List<TagDO> tagDOS = tagMapper.selectByKey(key);
        List<SelectRspVO> selectRspVOS = new ArrayList<>();
        if(tagDOS.size() > 0){
            selectRspVOS = tagDOS.stream().map(tagDO -> {
                SelectRspVO vo = new SelectRspVO();
                vo.setLabel(tagDO.getName());
                vo.setValue(tagDO.getId());
                return vo;
            }).collect(Collectors.toList());
        }
        return Response.success(selectRspVOS);
    }

    @Override
    public Response findTagSelectList() {
        List<TagDO> tagDOS = tagMapper.findAll();
        // DO 转 VO
        List<SelectRspVO> vos = null;
        if(tagDOS.size() > 0){
            vos = tagDOS.stream().map(tagDO -> SelectRspVO.builder()
                    .label(tagDO.getName())
                    .value(tagDO.getId()).build()).collect(Collectors.toList());
        }
        return Response.success(vos);
    }
}
